package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class AddressBookServiceImpl implements AddressBookService {

    @Autowired
    private AddressBookMapper addressBookMapper;

    /**
     * 新增地址
     * @param addressBook
     */
    @Override
    public void add(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(0);
        addressBookMapper.add(addressBook);
    }

    /**
     * 查询当前登录用户的所有地址信息
     * @return
     */
    @Override
    public List<AddressBook> list() {
        Long userid = BaseContext.getCurrentId();
        AddressBook addressBook = new AddressBook();
        addressBook.setUserId(userid);
        List<AddressBook> addressBooks=addressBookMapper.list(addressBook);
        return addressBooks;
    }

    /**
     * 根据id修改地址
     * @param addressBook
     */
    @Override
    public void updateById(AddressBook addressBook) {
        addressBookMapper.update(addressBook);
    }

    /**
     * 根据id删除地址
     * @param id
     */
    @Override
    public void deleteById(Long id) {
        addressBookMapper.deleteById(id);
    }

    /**
     * 查询默认地址
     * @return
     */
    @Override
    public List<AddressBook> listlist_default() {
        Long userid = BaseContext.getCurrentId();
        AddressBook addressBook = new AddressBook();
        addressBook.setUserId(userid);
        addressBook.setIsDefault(1);
        List<AddressBook> addressBooks=addressBookMapper.list(addressBook);
        return addressBooks;
    }

    /**
     * 根据id查询地址
     * @param id
     * @return
     */
    @Override
    public List<AddressBook> listById(Long id) {
        AddressBook build = AddressBook.builder()
                                          .id(id)
                                          .build();
        List<AddressBook> list = addressBookMapper.list(build);
        return list;
    }

    /**
     * 设置默认地址
     * @param addressBook
     */
    @Override
    public void update_dafault(AddressBook addressBook) {
        //1、将当前用户的所有地址修改为非默认地址 update address_book set is_default = ? where user_id = ?
        addressBook.setIsDefault(0);
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookMapper.updateAllDafaultByUserid(addressBook);
        //2、将当前地址改为默认地址 update address_book set is_default = ? where id = ?
        addressBook.setIsDefault(1);
        addressBookMapper.update(addressBook);
    }
}
